package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.SysRole;
import com.example.entity.SysUser;
import com.example.entity.SysUserRole;
import com.example.mapper.SysMenuMapper;
import com.example.mapper.SysRoleMapper;
import com.example.mapper.SysUserMapper;
import com.example.mapper.SysUserRoleMapper;
import com.example.utils.ShiroUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sysuser")
public class SysuserController extends BaseController {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysMenuMapper sysMenuMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @RequestMapping("/index")
    //@RequiresPermissions("/sysrole/index")
    public ModelAndView index(HttpServletRequest request) {
        Subject subject = ShiroUtils.getSubject();
        SysUser sysUserLogin = (SysUser) subject.getPrincipal();
        String method = request.getMethod();
        if ("POST".equals(method)) {
            Integer pageNo = Integer.valueOf(request.getParameter("page"));
            Integer pageSize = Integer.valueOf(request.getParameter("pageSize"));
            Page<Map> page = new Page<>(pageNo, pageSize);
            ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
            IPage<Map<String, Object>> sysUsers = sysUserMapper.selectListAndRoles(page);
            modelAndView.addObject("data", sysUsers);
            modelAndView.addObject("sysuser", sysUserLogin);
            return modelAndView;
        } else {
            ModelAndView modelAndView = new ModelAndView("page/sysuser/user");
            modelAndView.addObject("sysuser", sysUserLogin);
            return modelAndView;
        }
    }

    @RequestMapping("/add")
    //@RequiresPermissions("index:welcome")
    public ModelAndView add(HttpServletRequest request, SysUser sysUser) {
        Subject subject = ShiroUtils.getSubject();
        SysUser sysUserLogin = (SysUser) subject.getPrincipal();
        String method = request.getMethod();
        if ("POST".equals(method)) {
            String[] roleIds = request.getParameterValues("roleIds[]");
            ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
            sysUser.setPassword(ShiroUtils.sha256("123", "123"));
            sysUser.setSalt("123");
            sysUser.setCreateTime(new Timestamp(new Date().getTime()));
            sysUser.setCreateUserId(sysUserLogin.getId());
            try {
                sysUserMapper.insert(sysUser);
                Map<String, Object> map = new HashMap<>();
                map.put("user_id", sysUser.getId());
                sysUserRoleMapper.deleteByMap(map);
                if (roleIds != null) {
                    for (String roleId : roleIds) {
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setUserId(sysUser.getId());
                        sysUserRole.setRoleId(Long.parseLong(roleId));
                        sysUserRoleMapper.insert(sysUserRole);
                    }
                }
                modelAndView.addObject("sysUserLogin", sysUserLogin);
                modelAndView.addObject("code", 200);
                modelAndView.addObject("msg", "成功！");
            }catch (Exception e){
                modelAndView.addObject("code", 0);
                modelAndView.addObject("msg", e.getMessage());
            }
            return modelAndView;
        } else {
            ModelAndView modelAndView = new ModelAndView("page/sysuser/user_add");
            List<SysRole> roleList = sysRoleMapper.selectList(null);
            //modelAndView.addObject("roleList", JSON.toJSONString(roleList));
            modelAndView.addObject("roleList", (roleList));
            return modelAndView;
        }
    }

    @RequestMapping("/edit")
    //@RequiresPermissions("sysmenu/edit")
    public ModelAndView edit(HttpServletRequest request, SysUser sysUser) throws InterruptedException {
        Subject subject = ShiroUtils.getSubject();
        SysUser sysUserLogin = (SysUser) subject.getPrincipal();
        String method = request.getMethod();
        if ("POST".equals(method)) {
            String[] roleIds = request.getParameterValues("roleIds[]");
            ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
            sysUser.setCreateUserId(sysUserLogin.getId());
            if ("admin".equals(sysUser.getUsername()) && 0 == sysUser.getStatus()) {
                modelAndView.addObject("code", 0);
                modelAndView.addObject("msg", "超级用户不能禁用！");
            } else {
                sysUserMapper.updateById(sysUser);
                Map<String, Object> map = new HashMap<>();
                map.put("user_id", sysUser.getId());
                sysUserRoleMapper.deleteByMap(map);
                if (roleIds != null) {
                    for (String roleId : roleIds) {
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setUserId(sysUser.getId());
                        sysUserRole.setRoleId(Long.parseLong(roleId));
                        sysUserRoleMapper.insert(sysUserRole);
                    }
                }
                modelAndView.addObject("sysUserLogin", sysUserLogin);
                modelAndView.addObject("code", 200);
                modelAndView.addObject("msg", "成功！");
            }
            return modelAndView;
        } else {
            String id = request.getParameter("id");
            ModelAndView modelAndView = new ModelAndView("page/sysuser/user_edit");
            SysUser sysUserTemp = sysUserMapper.selectById(id);
            modelAndView.addObject("sysUser", sysUserTemp);
            List<SysRole> roleList = sysRoleMapper.selectList(null);
            //modelAndView.addObject("roleList", JSON.toJSONString(roleList));
            modelAndView.addObject("roleList", (roleList));
            List<SysRole> userRoleList = sysRoleMapper.selectListByUserId(Long.parseLong(id));
            modelAndView.addObject("userRoleList", JSON.toJSONString(userRoleList, SerializerFeature.WriteMapNullValue));
            return modelAndView;
        }
    }

    @RequestMapping("/delete")
    //@RequiresPermissions("sysmenu/delete")
    public ModelAndView delete(HttpServletRequest request, SysUser sysUser) throws InterruptedException {
        Subject subject = ShiroUtils.getSubject();
        SysUser sysUserLogin = (SysUser) subject.getPrincipal();
        String method = request.getMethod();
        String id = request.getParameter("id");
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());

        SysUser sysUserTemp = sysUserMapper.selectById(id);
        if ("admin".equals(sysUserTemp.getUsername())) {
            modelAndView.addObject("code", 0);
            modelAndView.addObject("msg", "超级用户不能删除！");
        } else {
            sysUserMapper.deleteById(id);
            Map<String, Object> map = new HashMap<>();
            map.put("user_id", id);
            sysUserRoleMapper.deleteByMap(map);
            modelAndView.addObject("sysUserLogin", sysUserLogin);
            modelAndView.addObject("code", 200);
            modelAndView.addObject("msg", "成功！");
        }

        return modelAndView;
    }

    @RequestMapping("/reset")
    //@RequiresPermissions("sysmenu/delete")
    public ModelAndView reset(HttpServletRequest request, SysUser sysUser) throws InterruptedException {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        Subject subject = ShiroUtils.getSubject();
        SysUser sysUserLogin = (SysUser) subject.getPrincipal();
        String method = request.getMethod();
        SysUser sysUserTemp = sysUserMapper.selectById(sysUser.getId());
        sysUser.setPassword(ShiroUtils.sha256(sysUser.getPassword(), sysUserTemp.getSalt()));
        int i = sysUserMapper.updateById(sysUser);
        modelAndView.addObject("sysUserLogin", sysUserLogin);
        modelAndView.addObject("code", 200);
        modelAndView.addObject("msg", "成功！");

        return modelAndView;
    }

    @RequestMapping("/userinfo")
    //@RequiresPermissions("index:welcome")
    public ModelAndView userinfo(HttpServletRequest request, SysUser sysUser) {
        Subject subject = ShiroUtils.getSubject();
        SysUser sysUserLogin = (SysUser) subject.getPrincipal();
        String method = request.getMethod();
        if ("POST".equals(method)) {
            String[] roleIds = request.getParameterValues("roleIds[]");
            ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
            sysUser.setSalt("123");
            sysUser.setCreateTime(new Timestamp(new Date().getTime()));
            sysUser.setCreateUserId(sysUserLogin.getId());
            sysUserMapper.insert(sysUser);
            Map<String, Object> map = new HashMap<>();
            map.put("user_id", sysUser.getId());
            sysUserRoleMapper.deleteByMap(map);
            if (roleIds != null) {
                for (String roleId : roleIds) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser.getId());
                    sysUserRole.setRoleId(Long.parseLong(roleId));
                    sysUserRoleMapper.insert(sysUserRole);
                }
            }
            modelAndView.addObject("sysUserLogin", sysUserLogin);
            modelAndView.addObject("code", 200);
            modelAndView.addObject("msg", "成功！");
            return modelAndView;
        } else {
            ModelAndView modelAndView = new ModelAndView("page/user_info");
            List<SysRole> roleList = sysRoleMapper.selectList(null);
            modelAndView.addObject("roleList", JSON.toJSONString(roleList));
            modelAndView.addObject("sysUserLogin", sysUserLogin);
            modelAndView.addObject("roleList", (roleList));
            return modelAndView;
        }
    }

}
